package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"strings"
)

var (
	tmplMaster []byte
	tmplSlave  []byte
)

type node struct {
	Cluster string
	Role    string   // master, slave
	ID      int      // id
	Addr    string   // cluster-ip
	Dbs     []string // databases
	Value   string   // all the value
}

func (n node) String() string {
	return fmt.Sprintf(`
Role:%s
Name:%s
Value:%s
`, n.Role, n.Name(), n.Value)
}

func (n *node) Name() string {
	if n.Role == "master" {
		return strings.ToLower(n.Cluster)
	}
	return fmt.Sprintf("%s-%d", strings.ToLower(n.Cluster), n.ID)
}

type jsonStruct struct {
	Cluster   string
	Master    string
	Slave     string
	Databases string
}

func (js *jsonStruct) ParseToNodes() []node {
	result := make([]node, 0, 4)
	dbs := `["` + strings.Join(strings.Split(js.Databases, ","), `","`) + `"]`
	if js.Master != "" {
		result = append(result, node{
			Cluster: strings.ToLower(js.Cluster),
			Role:    "master",
			Dbs:     strings.Split(js.Databases, ","),
			Addr:    js.Master,
			Value:   fmt.Sprintf(string(tmplMaster), js.Master, dbs),
		})
	}
	slaves := strings.Split(js.Slave, ",")
	for k, v := range slaves {
		if v != "" {
			result = append(result, node{
				Cluster: strings.ToLower(js.Cluster),
				Role:    "slave",
				ID:      k,
				Dbs:     strings.Split(js.Databases, ","),
				Addr:    v,
				Value:   fmt.Sprintf(string(tmplSlave), v, dbs),
			})
		}
	}
	return result
}

func load(file string, data interface{}) error {
	d, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}
	return json.Unmarshal(d, data)
}
